package com.superman.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.superman.domain.User;
import com.superman.service.UserService;
import com.superman.serviceImpl.UserServiceImpl;

/**
 * @function登录后台程序
 *
 * @author 竹叶青
 *
 *         2018年5月3日
 *
 */
public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//获取验证码，检验是否正确
		String in_checkcode = request.getParameter("checkcode");
		String real_checkcode = (String) request.getSession().getAttribute("checkcode");
		if (!real_checkcode.equalsIgnoreCase(in_checkcode)) {
			request.setAttribute("msg", "亲，您的验证码有误，请重新输入");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}else{
		//获取其余参数
			String email = request.getParameter("email");
			String password = request.getParameter("password");
			User user = new User();
			user.setEmail(email);
			user.setPassword(password);
			//检验用户是否存在
			UserService service = new UserServiceImpl();
			User loginUser = service.login(user);
			request.setAttribute("loginUser", loginUser);
			if (loginUser!=null) {
				String remember = request.getParameter("remember");
				if ("on".equalsIgnoreCase(remember)) {
					Cookie cookie = new Cookie("email", email);
					cookie.setMaxAge(60*60);
					response.addCookie(cookie);
					request.getRequestDispatcher("/index.jsp").forward(request, response);
				}else{
					Cookie cookie = new Cookie("email", "");
					cookie.setMaxAge(0);
					response.addCookie(cookie);
					request.getRequestDispatcher("/index.jsp").forward(request, response);
				}
				
			}else{
				request.setAttribute("msg", "用户名或密码错误");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
				return;
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}